/**
 * Created by zhangsr on 2020/7/6.
 */

var stream = weex.requireModule('stream') || {};
var eeui = app.requireModule('eeui');

const Json2Url=function(data)
{
    try {
        var tempArr = [];
        for (var i in data) {
            var key = i;
            var value = encodeURIComponent(data[i]);
            tempArr.push(key + '=' + value);
        }
        var urlParamsStr = tempArr.join('&');
        return urlParamsStr;
    } catch (err) {
        return '';
    }
}

const request=function(data) {
    var _this = this;
    return new Promise(function (resolve, reject) {

        var globalData = JSON.parse(eeui.getVariate("globalData"));

        var token = globalData.token

        var APP_BASE_API = globalData.APP_BASE_API;

        console.log(APP_BASE_API);

        // var APP_BASE_API = 'https://api.rzico.com:8443'

        var header = {}
        if (token != null) {
            header = {
                'Authorization': token,
                'Content-Type': 'application/json'
            }
        }

        var url = data.url;
        if (data.params != null && data.params != undefined) {
            var params = Json2Url(data.params)
            if (url.indexOf('?') >= 0) {
                url = url + '&' + params
            } else {
                url = url + '?' + params
            }
        }

        // console.info(APP_BASE_API + url)
        console.info("请求的数据--" + JSON.stringify(data))

        var apiUrl = '';
        if (url.indexOf('http') != -1) {
            apiUrl = url
        } else {
            apiUrl = APP_BASE_API + url
        }

        //console.log(apiUrl)

        stream.fetch({
            headers: header,
            method: data.method,
            url: apiUrl,
            type: 'json',
            body: data.data
        }, function (ret) {
            // console.info("服务端返回的数据ret--" + JSON.stringify(ret.data))
            console.log('数据')
            console.log(data.data)
            if (!ret.ok) {
                eeui.toast({
                    message: '请求出错',
                    gravity: 'middle'
                });
                reject(ret.statusText);
            } else {
                if (ret.data.type == "error") {
                    if (ret.data.content!=null) {
                        eeui.toast({
                            message: ret.data.content,
                            gravity: 'middle'
                        });

                    } else {
                        eeui.toast({
                            message: '请求出错',
                            gravity: 'middle'
                        });
                    }

                    reject(ret.data);
                } else {
                    resolve(ret.data);
                }

            }
        })
    });

}

export default request;
